package com.zang.tree;

import java.util.*;

/**
 * 二叉树的层序遍历II
 *
 * @author ZVerify
 * @since 2022/10/23 11:12
 * @see <a href="https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/submissions/">...</a>
 **/
public class 二叉树的层序遍历II {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) return Collections.emptyList();

        if (root.left == null && root.right == null) return Collections.singletonList(Collections.singletonList(root.val));

        LinkedList<List<Integer>> list = new LinkedList<>();

        Deque<TreeNode> queue = new LinkedList<>();
        queue.push(root);

        while (!queue.isEmpty()){
            ArrayList<Integer> arrayList = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size ; i++){
                TreeNode pollFirst = queue.poll();
                arrayList.add(pollFirst.val);
                if (pollFirst.left!=null) queue.offer(pollFirst.left);
                if (pollFirst.right!=null) queue.offer(pollFirst.right);
            }
            list.addFirst(arrayList);
        }

        return list;
    }
}
